var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var config=require('../config');
var User=require('./user')
var BbsPlate=require('./bbsPlate')
var db=mongoose.createConnection(config.db_url);
db.on('error',function(error){
    console.log(error);
});
db.model('User',User.userSchema);
db.model('BbsPlate',BbsPlate.bbsPlateSchema);
var postSchema=new Schema({
    publishUser:{type:Schema.Types.ObjectId,ref:'User'},
    bbsPlate:{type:Schema.Types.ObjectId,ref:'BbsPlate'},
    theme:String,
    content:String,
    state:{type:Number,default:0},
    postDate:{type:Date,default:Date.now},
    replyTotal:{type:Number,default:0},
    hitTotal:{type:Number,default:0}
});
//users---对应数据库表名
var Post=db.model('Post',postSchema);
Post.prototype.findAllPost=function (callback){
    Post.find({}).populate('publishUser bbsPlate').sort('postDate').exec(function(err,datas){
        callback(err,datas);
    })
}
Post.prototype.findPostByOptions=function (options,callback){
    Post.find(options).populate('publishUser bbsPlate').exec(function(err,datas){
        callback(err,datas);
    })
}
Post.prototype.findHotPosts=function (callback){
    Post.find({}).sort('-replyTotal').limit(5).populate('publishUser bbsPlate').exec(function(err,datas){
        callback(err,datas);
    })
}
Post.prototype.findPostByRelate=function (options,callback){
    Post.find(options).populate('publishUser').exec(function(err,datas){
        callback(err,datas);
    })
}
Post.prototype.findPostById=function (id,callback){
    Post.findOne({_id:id}).populate('publishUser bbsPlate').exec(function(err,data){
        callback(err,data);
    })
}
Post.prototype.updateStateById=function(id,state,callback){
    Post.update({_id:id},{state:state},function(err){
        return callback(err);
    })
}
Post.prototype.updateReplyTotalById=function (id,callback){
    Post.update({_id:id},{'$inc':{replyTotal:1}},function(err){
        callback(err);
    })
}
Post.prototype.updateHitTotalById=function (id,callback){
    Post.update({_id:id},{'$inc':{hitTotal:1}},function(err){
        callback(err);
    })
}

Post.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=Post.find(q,col).sort('-postDate').skip(obj.page.skipFrom).limit(obj.page.limit).populate('publishUser bbsPlate');
    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            Post.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    callback(null, count,pageCount, datas);
                }
            });
        }
    });

}
//分组查询：
Post.prototype.findActiveApplyGroup = function (options,callback) {
    //count这里用了$sum:1实现http://docs.mongodb.org/manual/reference/operator/aggregation/group/
    Post.aggregate()
        .match(options)      //条件
        .group({_id: '$publishUser', count: {$sum:1}})//count:指定一个字段，字段名可随意，1表示所有记录的count字段值为1,$sum在求和
        .sort('-count')                        //数组结果降序
        .project('_id')      //1表示字段返回，0：不返回
        .limit(8)                              //过滤条数
        .exec(function (err, groupDatas) {
            callback(err, groupDatas);
        });

}
module.exports = Post;
module.exports.postSchema=postSchema;